﻿using System;
using System.Collections;
using System.Web.UI.WebControls;

using Resources;
using Service;
using System.Data;


public partial class Department : System.Web.UI.Page
{

    readonly ReferenceDataService _ReferenceDataService = new ReferenceDataService();
    readonly StockService _StockService = new StockService();
    private Utility _utility = new Utility();
   
    protected void Page_Load(object sender, EventArgs e)
    {
      //  lblTotalDepartment.Text = "Total department:" + _ReferenceDataService.GetDepartments().Count;

        if (Session["whereClause"] == null)
            Session["whereClause"] = txtHiddenWhereClause.Text;
        if (Session["orderByClause"] == null)
            Session["orderByClause"] = txthiddenOrderbyClause.Text;

        new Utility().SetRowToDisplay(grdDepartment, Session["rowsToSDisplay"]);
        if (!IsPostBack)
        {
            // to avoid loading for the first time

            if (Session["pageIndex"] != null)
            {
                grdDepartment.PageIndex = Int32.Parse(Session["pageIndex"].ToString());

            }

            /* 
             * 1. number of equipments
             * 2. select the element 
             * */
            

        }
        else
        {
            txtHiddenPageIndex.Text = "0";
            // SystemList = new DirectService().DataTableToIlistSystem(GetWhereClause(), GetOrderClause());
             lblTotalDepartment.Text = "Total department : " + new DirectService().GetDepartmentDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            int number = +new DirectService().GetDepartmentDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            if (number == 0)
            {
                grdDepartment1.Visible = true;
            }
            else
            {
                grdDepartment.Visible = true; 
                grdDepartment1.Visible = false;
            }
        }
        grdDepartment.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text) ? Int32.Parse(txtHiddenPageIndex.Text) : 0;
    }

    protected string GetWhereClause()
    {
        string whereClause = string.Empty;
        string and = "";
        string str = "";

        // Prepare by equipement
        int i = 0;
        
        if(!string.IsNullOrEmpty(txtDepartmentId.Text))
        {
            if (int.TryParse(txtDepartmentId.Text, out i))
            {
                and = " and ";
                str = " where Department.DepartmentId=" + Int32.Parse(txtDepartmentId.Text);
                if (txtDepartmentLabel.Text != string.Empty)
                {
                    str += " " + "and" + " " + "Department.DepartmentName=" + "'" + txtDepartmentLabel.Text + "'";
                    and = " and ";
                }
            }
            else {
                grdDepartment.Visible = false; 
                grdDepartment1.Visible = true;
                lblTotalDepartment.Text = "Total department : 0";
                return null;
            }
        }
        else
        {
            if (txtDepartmentLabel.Text != string.Empty)
            {
                str += " " + "where" + " " + "Department.DepartmentName like" + "'%" + txtDepartmentLabel.Text + "%'";
                and = " and ";
            }
        }

        if (!String.IsNullOrEmpty(str))
            whereClause = str + " ";
        return whereClause;
    }
    protected string GetOrderClause()
    {
        return " Order by Department.DepartmentName";
    }
    protected void bntFilter_Click(object sender, EventArgs e)
    {
        
        Session["whereClause"] = GetWhereClause();
        Session["orderByClause"] = GetOrderClause();
        txthiddenOrderbyClause.Text = GetOrderClause();
        txtHiddenWhereClause.Text = GetWhereClause();
        Session["defaultTabIndex"] = 0;
        ClearControlSearch();
        ClearControlAdd();

    }
    private void ClearControlSearch()
    {
        txtDepartmentId.Text = "";
        txtDepartmentLabel.Text = ""; 
    }

    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }

    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?
                       Int32.Parse(Session["pageIndex"].ToString())
                   : 0;
    }
    private void ClearControlAdd()
    {
        txtDepartment.Text = "";
        lblMessageValidate.Text = "";
        lblMessage.Text = ""; 
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {

        
        //if (!new Utility().TestPermissions(Resource.PermisAddEquipment))
        //{
        //    lblMessageValidate.Text = "sdfd";
        //    return;
        //}

        AddDepartment();
        
  


    }
    private void AddDepartment()
    {
        IList list = new ArrayList();
        list = _StockService.GetDepartment();

        for (int i = 0; i < list.Count; i++)
        {
            if (((Model.Department)list[i]).DepartmentLabel == txtDepartment.Text)
            {
                lblMessage.Visible = true;
                lblMessageValidate.Text = ""; 
                return;
            }
            lblMessage.Visible = false;

        }
        if (txtDepartment.Text !="")
        {
            Model.Department _department = new Model.Department();
            _department.DepartmentId = 0;
            _department.DepartmentLabel = txtDepartment.Text;
            _ReferenceDataService.SaveDepartment(_department);
            // lblTotalDepartment.Text = "Total department:" + _ReferenceDataService.GetDepartments().Count;
            
            ClearControlAdd();
            lblMessageValidate.Text = Resource.MessageValidate;
        }
        
    }
    protected void grdDepartment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Delete"))
        {
            if (!new Utility().TestPermissions(Resource.PermissionDeleteDepartment))
            {
                lblPermission.Visible = true;
                lblPermission.Text = Resource.Permission;

                return;
            }
            int departmentId = Convert.ToInt32(grdDepartment.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
            _StockService.DeleteDepartment(departmentId);
            Response.Redirect("Department.aspx");
            new Utility().SetSelectedColorToGridView(e, grdDepartment);
        }
        
    }
    protected void grdDepartment_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //block to add message
            string stringComplete = "";
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                LinkButton deleteButton = (LinkButton)e.Row.Cells[1].Controls[0];
                deleteButton.Attributes.Add("onclick", "return confirm('" + Resources.Resource.ConfirmDeleteMessage + "');");
            }
        }
    }
    protected void grdDepartment_Sorted(object sender, EventArgs e)
    {
        grdDepartment.DataBind();
    }
    protected void grdDepartment_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Model.Department _department = new Model.Department();

        if (e.Cancel == false)
        {
            bool flag = true;
            if (flag == false)
            {
                GridViewRow row = grdDepartment.Rows[e.RowIndex];
                _department.DepartmentId = Int32.Parse(row.Cells[2].Text);
                _department.DepartmentLabel = row.Cells[4].Text;
            }
        }
    }
    protected void grdDepartment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdDepartment.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdDepartment.PageIndex.ToString();
        Session["pageIndex"] = grdDepartment.PageIndex;
    }

    protected void dsDepartment_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        //if (e.ReturnValue != null) lblTotalDepartment.Text ="Total Department:" + ((DataTable)e.ReturnValue).Rows.Count;
    }
    protected void grdDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void dsDepartment_Selected1(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.ReturnValue != null) lblTotalDepartment.Text = "Total department:" + ((DataTable)e.ReturnValue).Rows.Count;
    }
}



